<template>
  <div style="display: flex;">
    <div style=" width: 230px;">
      <a-textarea style="height: 700px;" v-model:value="keyword" placeholder="请输入关键词，一行一个。" />
      <div style="margin-top: 20px;display: flex;justify-content: space-between;">
        <a-button type="dashed" @click="emptyKeyWord">清空</a-button>
        <a-button type="primary"@click="analyse">开始分析</a-button>
      </div>
    </div>
    <div style="flex: 1;padding-left: 20px;">
      <div id="categoryEchart" style="width: calc(100% - 250px);height: 200px;" />
      <div id="lineEchart" style="width: calc(100% - 250px);height: 250px;" />
      <base-table
          title="评论分析" 
          :scroll="{y:150}" 
          size="small" 
          :data-source="tableData" 
          :columns="columns"
        >
      </base-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import { RateList } from '../index/commentAnalysis';
import { keywordStats, lineChartDataType } from './wordFrequencyAnalyse'
const props = defineProps<{
  commentSourceData: RateList[],
}>();

const keyword = ref<string>()
const dataList = ref<RateList[]>(props.commentSourceData.sort((a,b) => new Date(a.feedbackDate).getTime() - new Date(b.feedbackDate).getTime()))
const tableData = ref<keywordStats[]>([])
const categoryEchart = ref<echarts.ECharts | null>(null)
const lineEchart = ref<echarts.ECharts | null>(null)

const categoryOption = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '5%',
    right: '5%',
  },
  xAxis: [
    {
      type: 'category',
      data: [] as string[],
      axisTick: {
        alignWithLabel: true
      }
    }
  ],
  yAxis: [
    {
      type: 'value'
    }
  ],
  series: [
    {
      name: 'Direct',
      type: 'bar',
      barWidth: '60%',
      data: [] as number[]
    }
  ]
})
const lineOption = ref({
  grid: {
    left: '5%',
    right: '5%',
    bottom: '100px',
    containLabel: true
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    },
  },
  // dataZoom: [
  //   {
  //     type: 'inside',
  //     xAxisIndex: [0],
  //     start: 0,
  //     end: 100
  //   },
  //   {
  //     show: true,
  //     xAxisIndex: [0],
  //     type: 'slider',
  //     bottom: 40,
  //     start: 0,
  //     end: 100
  //   }
  // ],
  legend: {
    type: 'scroll',
    data: [] as string[]
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: [] as string[]
  },
  yAxis: {
    type: 'value'
  },
  series: [] as { name: string; type: string; stack: string; data: number[] }[]
})
const columns = ref([
  {
    dataIndex: 'keywordName',
    title: '关键词',
  },
  {
    dataIndex: 'commentNumber',
    title: '评论条数',
  },
  {
    dataIndex: 'commentPercentage',
    title: '占比',
  },
])

const setCategoryData = (arr: keywordStats[]) => {
  categoryOption.value.xAxis[0].data = arr.map(item => item.keywordName);
  categoryOption.value.series[0].data = arr.map(item => item.commentNumber);
  nextTick(() => {
    if (categoryEchart.value) {
      categoryEchart.value.setOption(categoryOption.value, true);
      categoryEchart.value.resize(); // 强制重绘图表
    }
  })
}

const setLineOptionData = (obj: lineChartDataType) => {
  lineOption.value.xAxis.data = obj.xAxisData;
  lineOption.value.legend.data = obj.legendData;
  lineOption.value.series = obj.seriesData;

  nextTick(() => {
    if (lineEchart.value) {
      lineEchart.value.setOption(lineOption.value, true);
      lineEchart.value.resize(); // 强制重绘图表
    }
  })
}

const setData = (arr: string[]) => {
  const lineChartData  = {
    legendData: [],
    xAxisData: [],
    seriesData: []
  } as lineChartDataType;
  
  // 存储每个关键词的评论次数和百分比
  const keywordStats = [] as keywordStats[];
  const setLineData = (item: RateList, keywordStr: string) => {
    let series = lineChartData.seriesData.find(series => series.name === keywordStr);
    if (!series) {
      series = {
        name: keywordStr,
        type: 'line',
        stack: '',
        smooth: true,
        data: []
      };
      lineChartData.seriesData.push(series);
      lineChartData.legendData.push(keywordStr);
    }
    let dateIndex = lineChartData.xAxisData.indexOf(item.feedbackDate);
    if (dateIndex === -1) {
      lineChartData.xAxisData.push(item.feedbackDate);
      series.data.push(1);
    } else {
      series.data[dateIndex] += 1;
    }
  };
  const setDataList = (keywordStr: string) => {
    let keywordStat = keywordStats.find(stat => stat.keywordName === keywordStr);
    if (!keywordStat) {
      keywordStat = {
        keywordName: keywordStr,
        commentNumber: 0,
        commentPercentage: 0
      };
      keywordStats.push(keywordStat);
    }
    keywordStat.commentNumber += 1;
    keywordStat.commentPercentage = (keywordStat.commentNumber / dataList.value.length) * 100;
  };
  dataList.value.forEach(item => {
    const feedback = item.feedback; // 首次评论内容
    const appendedFeedback = item.appendedFeedback; // 追评内容
    arr.forEach(keywordStr => {
      if (feedback.includes(keywordStr) || appendedFeedback.includes(keywordStr)) {
        setDataList(keywordStr);
        setLineData(item, keywordStr);
      }
    });
  });
   // 添加没有找到值的关键词默认数据
   arr.forEach(keywordStr => {
    if (!keywordStats.find(stat => stat.keywordName === keywordStr)) {
      keywordStats.push({
        keywordName: keywordStr,
        commentNumber: 0,
        commentPercentage: 0
      });
    }
    if (!lineChartData.seriesData.find(series => series.name === keywordStr)) {
      lineChartData.seriesData.push({
        name: keywordStr,
        type: 'line',
        stack: '',
        smooth: true,
        data: Array(lineChartData.xAxisData.length).fill(0)
      });
      lineChartData.legendData.push(keywordStr);
    }
  });
  setCategoryData(keywordStats)
  setLineOptionData(lineChartData)
  tableData.value = keywordStats;
  console.log("🚀 ~ setData ~ lineChartData:", lineChartData)
  console.log("🚀 ~ setData ~ keywordStats:", keywordStats)
}

const analyse = () => {
  if (!keyword.value) return
  const keywordArr = keyword.value.split("\n")
  const uniqueKeywordArr  = Array.from(new Set(keywordArr)) 
  console.log("🚀 ~ analyse ~ uniqueKeywordArr:", uniqueKeywordArr)
  setData(uniqueKeywordArr)
}

const emptyKeyWord = () => {
  keyword.value = ""
}

onMounted(() => {
  categoryEchart.value =  markRaw(echarts.init( document.getElementById('categoryEchart')))
  lineEchart.value =  markRaw(echarts.init( document.getElementById('lineEchart')))
})
</script>

<style lang="less" scoped>

</style>